/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.tedu.mall.ams.service.impl;

import cn.tedu.mall.ams.mapper.AdminMapper;
import cn.tedu.mall.ams.mapper.AdminRoleMapper;
import cn.tedu.mall.ams.service.IAdminService;
import cn.tedu.mall.common.enums.LeafKey;
import cn.tedu.mall.common.exception.CoolSharkServiceException;
import cn.tedu.mall.common.pojo.admin.dto.AdminAddDTO;
import cn.tedu.mall.common.pojo.admin.dto.AdminQueryDTO;
import cn.tedu.mall.common.pojo.admin.dto.AdminUpdateDTO;
import cn.tedu.mall.common.pojo.admin.model.Admin;
import cn.tedu.mall.common.pojo.admin.vo.AdminVO;
import cn.tedu.mall.common.restful.JsonPage;
import cn.tedu.mall.common.restful.ResponseCode;
import cn.tedu.mall.common.service.ISegmentService;
import com.alibaba.druid.util.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import java.time.Duration;
import java.util.List;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 管理员表 服务实现类
 * </p>
 *
 * @since 2021-12-02
 */
@Service
public class AdminServiceImpl implements IAdminService {

    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private AdminRoleMapper adminRoleMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @DubboReference
    private ISegmentService segmentService;

    @Override
    public void addAdmin(AdminAddDTO adminDTO) {
        checkPassword(adminDTO.getPassword(), adminDTO.getPasswordAct());
        //转化bean
        Admin admin = new Admin();
        BeanUtils.copyProperties(adminDTO, admin);
        //补充id
        Long id = segmentService.getId(LeafKey.ADMIN.getKey()).getId();
        admin.setId(id);
        //密码加密
        admin.setPassword(passwordEncoder.encode(admin.getPassword()));
        adminMapper.insertAdmin(admin);
    }

    @Override
    public JsonPage<AdminVO> queryAdmins(Integer pageNum, Integer sizeNum, String query) {
        if (StringUtils.isEmpty(query)) {
            return listAdmins(pageNum, sizeNum);
        }
        PageHelper.startPage(pageNum, sizeNum);
        List<AdminVO> adminVOList = adminMapper.selectAdminsByUsername(query);
        PageInfo pageInfo = PageInfo.of(adminVOList);
        return JsonPage.restPage(pageInfo);
    }

    @Override
    public void updateAdmin(AdminUpdateDTO adminUpdateDTO) {
        Admin admin = new Admin();
        BeanUtils.copyProperties(adminUpdateDTO, admin);
        checkPassword(adminUpdateDTO.getPassword(), adminUpdateDTO.getPasswordAct());
        admin.setPassword(passwordEncoder.encode(admin.getPassword()));
        adminMapper.updateAdmin(admin);
    }

    @Override
    public void deleteAdmin(Long id) {
        adminMapper.deleteAdmin(id);
        adminRoleMapper.deleteAdminRole(id);
    }

    @Override
    public AdminVO queryOneAdmin(String username) {
        return adminMapper.selectAdminByUsername(username);
    }

    @Override
    public void enableAdmin(Long id, Integer enable) {
        if (enable != 0 && enable != 1) {
            throw new CoolSharkServiceException(ResponseCode.BAD_REQUEST, "启用数据传递错误");
        }
        adminMapper.updateAdminEnable(id, enable);
    }

    @Override
    public JsonPage<AdminVO> queryListAdmin(AdminQueryDTO adminQueryDTO) {
        //校验参数
        validateQuery(adminQueryDTO);
        //开启分页
        PageHelper.startPage(adminQueryDTO.getPage(), adminQueryDTO.getPageSize());
        List<AdminVO> adminVOList = adminMapper.selectAdminsByQuery(adminQueryDTO);
        PageInfo pageInfo = PageInfo.of(adminVOList);
        return JsonPage.restPage(pageInfo);
    }

    private void validateQuery(AdminQueryDTO adminQueryDTO) {
        //页数为空创建默认
        if (adminQueryDTO.getPage() == null) {
            adminQueryDTO.setPage(1);
        }
        if (adminQueryDTO.getPageSize() == null) {
            adminQueryDTO.setPageSize(5);
        }
        //日期校验
        if (adminQueryDTO.getStartCreateTime() != null && adminQueryDTO.getEndCreateTime() != null) {
            Duration between = Duration.between(adminQueryDTO.getStartCreateTime(), adminQueryDTO.getEndCreateTime());
            long l = between.toMillis();
            if (l < 0) {
                //说明结束时间小于起始时间
                throw new CoolSharkServiceException(ResponseCode.BAD_REQUEST, "结束创建时间不能小于起始创建时间");
            }
        }
        //日期校验
        if (adminQueryDTO.getStartModifiedTime() != null && adminQueryDTO.getEndModifiedTime() != null) {
            Duration between = Duration.between(adminQueryDTO.getStartModifiedTime(), adminQueryDTO.getEndModifiedTime());
            long l = between.toMillis();
            if (l < 0) {
                //说明结束时间小于起始时间
                throw new CoolSharkServiceException(ResponseCode.BAD_REQUEST, "结束修改时间不能小于起始修改时间");
            }
        }

        //排序
        if (adminQueryDTO.getOrderRule() == null) {
            adminQueryDTO.setOrderRule("desc");
        } else {
            String orderRule = adminQueryDTO.getOrderRule();
            if (!(orderRule.equals("desc") || orderRule.equals("asc"))) {
                throw new CoolSharkServiceException(ResponseCode.BAD_REQUEST, "您的排序规则传递错误,请表达desc 或者 asc");
            }
        }
    }

    //检查密码
    private void checkPassword(String password, String passwordAct) {
        if (!StringUtils.equals(password, passwordAct)) {
            throw new CoolSharkServiceException(ResponseCode.BAD_REQUEST, "两次输入的密码不正确");
        }
    }

    @Override
    public JsonPage<AdminVO> listAdmins(Integer pageNum, Integer sizeNum) {
        PageHelper.startPage(pageNum, sizeNum);
        List<AdminVO> adminVOList = adminMapper.selectAdmins();
        PageInfo pageInfo = PageInfo.of(adminVOList);
        return JsonPage.restPage(pageInfo);

    }
}
